<template>
    <a-layout id="layout-forgetPwd">
        <a-layout-header :style="headerStyle">
            <img :src="logo" class="logo" />{{name}}
        </a-layout-header>
        <a-layout-content :style="contentStyle">

            <a-row type="flex" justify="center" align="middle" style="height:100%;flex:1;">
                <!-- //轮播图 -->
                <a-col>
                    <a-carousel autoplay arrows class="my-carousel">
                        <div slot="prevArrow" class="custom-slick-arrow" style="left: 10px;z-index: 1">
                            <a-icon type="left-circle" />
                        </div>
                        <div slot="nextArrow" class="custom-slick-arrow" style="right: 10px">
                            <a-icon type="right-circle" />
                        </div>
                        <div v-for="(item,index) in loginImages" :key="index" style="height:500px;">
                            <img :src="item.imgUrl" />
                        </div>
                    </a-carousel>
                </a-col>
                <a-col>
                    <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout" class="register-body">
                        <a-form-model-item :wrapper-col="{ span: 24}" class="register-header">
                            找回密码
                        </a-form-model-item>
                        <a-form-model-item has-feedback prop="userPhone">
                            <template slot="label"><span class="required-start">*</span>手机号码</template>
                            <a-input v-model.number="ruleForm.userPhone" />
                        </a-form-model-item>
                        <a-form-model-item has-feedback v-show="isShowImgCode" prop="imgCode">
                            <template slot="label"><span class="required-start">*</span>图片验证码</template>
                            <a-input v-model="ruleForm.imgCode" autocomplete="off" style="width:120px;" />
                            <div class="code" @click="referTimestamp">
                                <img :src="verifyCodeUrl" @click="referTimestamp" />
                            </div>
                        </a-form-model-item>
                        <a-form-model-item has-feedback prop="vCode">
                            <template slot="label"><span class="required-start">*</span>验证码</template>
                            <a-input v-model.number="ruleForm.vCode" autocomplete="off" style="width:120px;" />
                            <div class="code" @click="sendSms" :style="fontColor">{{codeCotent}}</div>
                        </a-form-model-item>
                        <a-form-model-item has-feedback prop="password">
                            <template slot="label"><span class="required-start">*</span>登录密码</template>
                            <a-input v-model="ruleForm.password" type="password" autocomplete="off" />
                        </a-form-model-item>
                        <a-form-model-item has-feedback prop="checkPassword">
                            <template slot="label"><span class="required-start">*</span>确认密码</template>
                            <a-input v-model="ruleForm.checkPassword" type="password" autocomplete="off" />
                        </a-form-model-item>
                        <a-form-model-item :wrapper-col="{ span: 24}" class="reg-btn">
                            <a-button type="primary" @click="submitForm('ruleForm')">保存</a-button>
                            <a-button class="offset-sm-2 offset-2" @click="resetForm('ruleForm')">重置</a-button>
                        </a-form-model-item>
                        <!-- <a-form-model-item :wrapper-col="{ span: 20,offset: 4}">
                <router-link to="login" class="text-center">我已经注册了用户</router-link>
              </a-form-model-item> -->
                    </a-form-model>
                </a-col>
            </a-row>
        </a-layout-content>
        <a-layout-footer :style="footerStyle">{{copy}} <a href="http://beian.miit.gov.cn" target="_blank">{{ipc}}</a> 客服电话：{{phone}}</a-layout-footer>
    </a-layout>
</template>
<script>
import logo from "@/assets/logo.png";
import { LoginConfig } from "@/api/login";
import { checkUser, sendForgetPwdCode, resetPwd } from "@/api/user";

export default {
    metaInfo () {
        return {
            title: this.title,
            meta: this.meta
        }
    },
    computed: {
        verifyCodeUrl: function () {
            const { verifyCode, timestamp } = this;
            return verifyCode + timestamp;
        }
    },
    data () {
        let checkPhone;
        let checkCode;
        let numReg = /^[0-9]*$/;

        //手机号校验
        let checkUserPhone = (rule, value, callback) => {
            clearTimeout(checkPhone);
            if (!value) {
                return callback(new Error("请输入手机号"));
            }
            checkPhone = setTimeout(() => {
                if (!Number.isInteger(value)) {
                    callback(new Error("手机号格式不正确"));
                } else {
                    if (String(value).length != 11) {
                        callback(new Error("手机号格式不正确"));
                    } else {
                        this.isShowImgCode = true;
                        callback();
                    }
                }
            }, 100);
        };
        //图片验证码校验
        let checkImgCode = (rule, value, callback) => {
            if (!value) {
                callback(new Error("验证码不能为空"));
            } else if (value.length == 4) {
                callback();
            } else {
                callback(new Error("验证码不正确"));
            }
        };
        //验证码校验
        let checkVCode = (rule, value, callback) => {
            if (!value) {
                callback(new Error(" "));
            } else if (!Number.isInteger(value)) {
                callback(new Error("验证码格式不正确"));
            } else if (String(value).length != 6) {
                callback(new Error("验证码格式不正确"));
            } else {
                checkUser({ userPhone: this.ruleForm.userPhone, code: value }).then(
                    response => {
                        if (response.code == 200) {
                            callback();
                        } else {
                            callback(new Error(response.message));
                        }
                    }
                );
            }
        };
        //密码校验
        let validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (value.length < 6 || value.length > 14) {
                    callback(new Error("密码长度为6~14个字符"));
                }
                if (new RegExp(numReg).test(value)) {
                    callback(new Error("密码不能是纯数字"));
                }
                if (this.ruleForm.checkPassword !== "") {
                    this.$refs.ruleForm.validateField("checkPassword");
                }
                callback();
            }
        };
        let validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.ruleForm.password) {
                callback(new Error("密码不一致,请重新输入!"));
            } else {
                callback();
            }
        };
        return {
            headerStyle: {},  //头部样式
            contentStyle: {
                backgroundRepeat: "round",
            },            //中部样式
            footerStyle: {},             //底部样式
            logo,                       //logo
            name: "",         //网址名称
            copy: "© 2019",              //版权信息
            phone: "188200",             //客服电话
            ipc: "渝IPCP备",             //备案信息
            title: "",
            meta: [],
            status: 1,                   //网站状态(0:关闭 1:开启)
            cause: "系统维护...",         //关闭原因
            ruleForm: {
                password: "",
                checkPassword: "",
                userPhone: "",
                imgCode: "",
                vCode: "",
                userType: 1
            },
            rules: {
                password: [{ validator: validatePass, trigger: "change" }],
                checkPassword: [{ validator: validatePass2, trigger: "change" }],
                userPhone: [{ validator: checkUserPhone, trigger: "change" }],
                imgCode: [{ validator: checkImgCode, trigger: "change" }],
                vCode: [{ validator: checkVCode, trigger: "change" }],
            },
            layout: {
                labelCol: { span: 7 },
                wrapperCol: { span: 14 }
            },
            codeCotent: "获取验证码",
            fontColor: "",
            isShowCompany: true,
            form: this.$form.createForm(this, { name: "advanced_search" }),
            verifyCode: this.$Global.ApiBaseUrl + "/verifyCode/forgetPwdImageCode?timestamp=", //图片验证码地址
            timestamp: new Date().getTime(),
            isShowImgCode: false,
            loginImages: [],                       //轮播图
        };
    },
    created () {
        this.LoginConfig();
    },
    methods: {
        //获取登录页 配置
        LoginConfig () {
            LoginConfig().then(res => {
                const { headerStyle, contentStyle, footerStyle } = this;
                const { code, data, message } = res;
                if (code == 200) {
                    const { name, logo, copy, phone, ipc, title, backColor, backImgUrl, keyWord, description, status, cause, loginImages } = data;
                    Object.assign(contentStyle, {
                        backgroundColor: backColor,
                        backgroundImage: `url(${backImgUrl})`,
                    });
                    Object.assign(headerStyle, {
                        backgroundColor: backColor,
                    });
                    Object.assign(footerStyle, {
                        backgroundColor: backColor,
                    });
                    let meta = new Array();
                    if (keyWord) {
                        meta.push({                 // set meta
                            name: 'keyWords',
                            content: keyWord
                        })
                    }
                    if (description) {
                        meta.push({                 // set meta
                            name: 'description',
                            content: description
                        })
                    }
                    Object.assign(this, {
                        title, name, logo, copy, phone, ipc, loginImages, meta
                    })
                    console.log("this.meta:", this.meta, this.loginImages)
                }
            })
        },
        submitForm (formName) {
            console.log("===找回密码===");
            this.$refs[formName].validate(valid => {
                if (valid) {
                    resetPwd(this.ruleForm).then(response => {
                        if (response.code == 200) {
                            this.$message.success("修改密码成功");
                            this.$store.dispatch("Logout").then(() => {
                                this.$router.push({ path: "login" });
                            });
                        }
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        //发送短信验证码
        sendSms () {
            this.$refs["ruleForm"].validateField("userPhone", valid => {
                if (!valid) {
                    this.$refs["ruleForm"].validateField("imgCode", valid => {
                        if (!valid) {
                            sendForgetPwdCode({
                                userPhone: this.ruleForm.userPhone,
                                imgCode: this.ruleForm.imgCode
                            }).then(response => {
                                if (response.code == 200) {
                                    this.$message.success("发送成功");

                                    let t = 60;
                                    this.fontColor = "color: #caced6; pointer-events: none;";
                                    let code = setInterval(() => {
                                        if (t == 0) {
                                            this.codeCotent = "获取验证码";
                                            this.fontColor = "";
                                            clearInterval(code);
                                            return false;
                                        }
                                        this.codeCotent = "获取验证码(" + t-- + ")";
                                    }, 1000);
                                } else {

                                    this.timestamp = new Date().getTime();
                                }
                            });
                        }
                    });
                }
            });
        },
        //重置表单
        resetForm (formName) {
            this.$refs[formName].resetFields();
        },
        //重置密码
        resetPwd (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => { });
        },
        changeType (value) {
            const type = this.ruleForm.userType;
            console.log("type", this.ruleForm.userType);
            if (type == 1) {
                this.isShowCompany = true;
            } else {
                this.isShowCompany = false;
            }
        },
        getUrlKey (name, url) {
            return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
        },
        //刷新时间
        referTimestamp () {
            this.timestamp = new Date().getTime();
        }
    }
};
</script>
<style lang="less" >
    #layout-forgetPwd {
        @media (min-width: 700px) {
            .my-carousel {
                width: 700px !important;
            }
        }
        @media (max-width: 700px) {
            .my-carousel {
                width: 100vw;
            }
        }
        @media (max-width: 430px) {
            .register-body {
                width: 92vw !important;
            }
        }
        .my-carousel {
            .slick-list {
                height: 500px;
                img {
                    max-height: 100%;
                }
            }
        }
        height: 100%;
        width: 100%;
        //头部样式
        .ant-layout-header {
            height: 70px;
            background: #fff;
            color: #333;
            font-size: 2rem;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
        }
        //中部样式
        .ant-layout-content {
            min-height: auto;
        }
        //底部
        .ant-layout-footer {
            background: #fff;
            text-align: center;
        }

        //轮播图样式
        .ant-carousel .slick-slide {
            text-align: center;
            // height: 160px;
            // line-height: 160px;
            // background: #364d79;
            overflow: hidden;
        }
        .ant-carousel .custom-slick-arrow {
            width: 25px;
            height: 25px;
            font-size: 25px;
            color: #0069d9;
            background-color: rgba(31, 45, 61, 0.11);
            opacity: 0.3;
        }
        .ant-carousel .custom-slick-arrow:before {
            display: none;
        }
        .ant-carousel .custom-slick-arrow:hover {
            opacity: 0.5;
        }

        .ant-carousel .slick-slide h3 {
            color: #fff;
        }

        .ant-carousel .slick-dots {
            height: auto;
        }
        .ant-carousel .slick-slide img {
            // border: 5px solid #fff;
            display: block;
            margin: auto;
            max-width: 80%;
        }
        .ant-carousel .slick-thumb {
            bottom: -45px;
        }
        .ant-carousel .slick-thumb li {
            width: 60px;
            height: 45px;
        }
        .ant-carousel .slick-thumb li img {
            width: 100%;
            height: 100%;
            filter: grayscale(100%);
        }
        .ant-carousel .slick-thumb li.slick-active img {
            filter: grayscale(0%);
        }

        //注册 主体
        .register-body {
            width: 430px;
            background: #ffffff;
            box-shadow: 0 0 1px rgba(0, 0, 0, 0.125), 0 1px 3px rgba(0, 0, 0, 0.2);
            padding: 10px 20px;
        }

        .logo {
            height: 100%;
        }
        .ant-form-item {
            margin-bottom: 10px !important;
        }
        .reg-btn .ant-form-item-children {
            display: flex;
            justify-content: center;
        }
        .register-header {
            text-align: center;
            font-size: 2.1rem;
        }
        .form-inline label {
            justify-content: left !important;
        }
        .form-inline > .col {
            margin-bottom: 1.5rem !important;
        }
        .icons-list /deep/ .anticon {
            margin-right: 8px;
            font-size: 16px;
        }
        .ant-advanced-search-form {
            padding: 24px;
            background: #fbfbfb;
        }

        .ant-advanced-search-form .ant-form-item {
            display: flex;
        }

        .ant-advanced-search-form .ant-form-item-control-wrapper {
            flex: 1;
        }

        #components-form-demo-advanced-search .ant-form {
            max-width: none;
        }
        #components-form-demo-advanced-search .search-result-list {
            margin-top: 16px;
            background-color: #fafafa;
            min-height: 200px;
            text-align: center;
            padding-top: 80px;
        }
        .code {
            float: right;
            width: auto;
            height: 32px;
            cursor: pointer;
            text-align: center;
        }
    }
</style>
